package com.fs.sys.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.annotations.Auth;
import com.fs.sys.bean.dto.TenantDTO;
import com.fs.sys.bean.dto.UserDTO;
import com.fs.sys.bean.query.TenantQuery;
import com.fs.sys.bean.req.TenantAddReq;
import com.fs.sys.bean.resp.TenantResp;
import com.fs.sys.service.TenantService;
import com.fs.sys.entityservice.TenantEntityService;
import com.fs.sys.entityservice.UserEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户控制器 
 * @author Coder Generator 2025-06-13 18:13:50 
 **/
@RestController
@RequestMapping("/sys/tenant")
@Slf4j
@Tag(name = "租户控制器")
public class TenantController {
    @Autowired
    private TenantEntityService service;

    @Autowired
    private UserEntityService userEntityService;

    @Autowired
    private TenantService tenantService;

    @PostMapping("add")
    @Operation(summary = "新增")
    @Auth
    public void add(@RequestBody @Validated TenantAddReq req) {
        tenantService.add(req);
    }

    @PutMapping("update")
    @Operation(summary = "更新")
    @Auth
    public void update(@RequestBody @Validated TenantDTO req) {
        service.update(req);
    }

    @DeleteMapping("delete/{id}")
    @Operation(summary = "删除")
    @Auth
    public void delete(@PathVariable("id") String id) {
        service.delete(id);
    }

    @GetMapping("detail/{id}")
    @Operation(summary = "根据id查找记录")
    public TenantResp findById(@PathVariable("id") String id) {
        TenantDTO dto = service.findById(id).orElse(null);
        if (null == dto) {
            return null;
        }
        return this.dtoToResp(Collections.singletonList(dto)).get(0);
    }

    @PostMapping("page-query")
    @Operation(summary = "查询-分页")
    public IPage<TenantResp> pageQuery(@RequestBody TenantQuery query) {
        IPage<TenantDTO> pageData = service.pageQuery(query);
        List<TenantResp> list = this.dtoToResp(pageData.getRecords());
        IPage<TenantResp> result = new Page<>();
        result.setTotal(pageData.getTotal());
        result.setRecords(list);
        return result;
    }

    @PostMapping("query")
    @Operation(summary = "查询-不分页")
    public List<TenantResp> query(@RequestBody TenantQuery query) {
        return dtoToResp(service.query(query));
    }

    /**
     * 租户返回数据转换
     * @param list 原始数据
     * @return 转换后数据
     */
    private List<TenantResp> dtoToResp(List<TenantDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>(16);
        }

        List<String> adminIds = list.stream().map(TenantDTO::getAdminId).toList();
        Map<String, UserDTO> userMap = userEntityService.findByIds(adminIds)
                .stream()
                .collect(Collectors.toMap(UserDTO::getId, u -> u));
        return list.stream()
                .map(item -> {
                    TenantResp resp = new TenantResp();
                    BeanUtils.copyProperties(item, resp);
                    resp.setAdmin(userMap.get(item.getAdminId()));
                    return resp;
                }).toList();
    }
}